//
//  AddUserLineVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/3.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AddUserLineVC.h"
#import "TopBackView.h"
#import "LineTableViewCell.h"
#import "Common.h"
#import "WKProgressHUD.h"

@interface AddUserLineVC ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate>

@property (nonatomic,strong) UIPickerView *pickerView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic) NSInteger number;

@property (nonatomic,strong) NSMutableDictionary *postDic;

@property (nonatomic) int isDelete;

@end

@implementation AddUserLineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"意愿线路"];
    
    self.dataArray = [NSMutableArray array];
    _number = 0;
    _isDelete = 0;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = GrayColor;
    
    [self initSubViews];
}

-(void)initSubViews
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, cellHeight * 2 -0.5) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    
    //orderid为空 说明是新增   有值说明是编辑
    
    NSString *string;
    
    
    if (self.orderId == nil) {
        
        self.postDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"",@"departProvinceCode",@"",@"departProvinceName",@"",@"receiptProvinceCode",@"",@"receiptProvinceName", nil];
        
        string = @"新增线路";

        
        [self getCityListWith:0];

    } else {
        
        self.postDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.startCityCode,@"departProvinceCode",self.startCityName,@"departProvinceName",self.endCityCode,@"receiptProvinceCode",self.endCityName,@"receiptProvinceName",self.orderId,@"id", nil];
        
        string = @"保存";

    }
    

    
    [self.view addSubview:self.tableView];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(18, CGRectGetMaxY(self.tableView.frame) + 20, screenWidth - 36, Button_height);
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [addButton setTitle:string forState:UIControlStateNormal];
    [addButton setBackgroundColor:YellowColor];
    [addButton addTarget:self action:@selector(addLines) forControlEvents:UIControlEventTouchUpInside];
    addButton.layer.cornerRadius = 5;
    [self.view addSubview:addButton];
}

-(void)initPickerVIew
{
    
    _isDelete = 1;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, screenHeight - 200, screenWidth, 200)];
    view.backgroundColor = WhiteColor;
    view.tag = 600;
    
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 40)];
    [view addSubview:topView];
    topView.backgroundColor = Color_RGB(200, 200, 200, 1);
    
    
    UIButton *leftBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"取消"forState:UIControlStateNormal];
    leftBtn.frame=CGRectMake(18, 0, 60, 40);
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 0, screenWidth - 200, 40)];
    label.text = @"地址选择";
    [topView addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = Font(15);
    
    //pickview    右选择按钮的文字
    UIButton *rightBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.frame=CGRectMake(screenWidth - 78, 0, 60, 40);
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];

    
    [topView addSubview:leftBtn];
    [topView addSubview:rightBtn];
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, screenWidth, 160)];

    
    [UIView animateWithDuration:0.3 animations:^{
        

    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [view addSubview:self.pickerView];

    } completion:^(BOOL finished) {
        
        [self.view addSubview:view];
        
    }];
    
    
    self.pickerView.backgroundColor = WhiteColor;
    
    self.pickerView.showsSelectionIndicator=YES;
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    
}

-(void)dismissView
{
    UIView *view = [self.view viewWithTag:600];
    
    [UIView animateWithDuration:0.3 animations:^{
       
        view.alpha = 0;
    } completion:^(BOOL finished) {
        
        _isDelete = 0;
        
        [view removeFromSuperview];
    }];
}




#pragma mark picker 代理 数据源
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}


-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.dataArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return  self.dataArray[row][@"name"];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (row > 0 && _number == 0) {
        
        if (_number == 0) {
            
            [self.postDic setObject:self.dataArray[0][@"name"] forKey:@"departProvinceName"] ;
            [self.postDic setObject:self.dataArray[0][@"code"] forKey:@"departProvinceCode"] ;
            
        } else {
            
            [self.postDic setObject:self.dataArray[row][@"name"] forKey:@"receiptProvinceName"];
            [self.postDic setObject:self.dataArray[row][@"code"] forKey:@"receiptProvinceCode"];
        }
        
        
    } else {
        
        LineTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
      
    
        [self.postDic setObject:self.dataArray[row][@"name"] forKey:@"receiptProvinceName"];
        [self.postDic setObject:self.dataArray[row][@"code"] forKey:@"receiptProvinceCode"];

        cell.startL.text = self.dataArray[row][@"name"];
    }
    
}

//添加路线
-(void)addLines
{
    
    //编辑路线
    if (self.orderId != nil) {

        NSString  *urlString = [NSString stringWithFormat:@"%@addr/modify",Main_interface];
       
        [[Common shared] afPostRequestWithUrlString:urlString parms:self.postDic finishedBlock:^(id responseObj) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            
            if ([dic[@"success"] boolValue]) {
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
                
            }
            
            
        } failedBlock:^(NSString *errorMsg) {
            
            NSLog(@"%@",errorMsg);
            
        }];

    
    } else {
   //新增路线
        
        
        //判断选择器是否收回
        if (_isDelete == 1) {
            [self dismissView];
        }
        
        
        
   NSString  *urlString = [NSString stringWithFormat:@"%@addr/modify",Main_interface];
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:urlString parms:self.postDic finishedBlock:^(id responseObj) {
       
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

        
        if ([dic[@"success"] boolValue]) {
           
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });

        }
        
        
    } failedBlock:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
        
    }];
        
    }
    

}

#pragma mark table 代理 数据源

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *string = @"CenterCell";
    LineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[LineTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.row == 0) {
        cell.titleL.text = @"起运地";
    } else {
        cell.titleL.text = @"目的地";

    }
    
    
    if (self.orderId != nil ) {
        
        if (indexPath.row == 0) {
            cell.startL.text = self.postDic[@"departProvinceName"];
        } else {
            cell.startL.text = self.postDic[@"receiptProvinceName"];

        }
        
    }
    
    
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _number = indexPath.row;
    
    [self getCityListWith:indexPath.row];
    
}

-(void)getCityListWith:(NSInteger)integer
{
    if (self.dataArray.count >0) {
        
        [self.dataArray removeAllObjects];
        
    }
    
    NSString *urlString ;
    
    if (integer == 0){
        
        urlString = [NSString stringWithFormat:@"%@area/list?params=%@",Main_interface,@"depart"];

    } else {
        
      urlString = [NSString stringWithFormat:@"%@area/list?params=%@",Main_interface,@"NO"];
    }
    
    [Common requestWithUrlString:urlString contentType:application_json errorShow:YES finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
            if ([responseObj[@"data"] count] > 0) {
                
                self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
                
                if (self.dataArray.count == 1) {
                    
                    NSLog(@"%@",self.dataArray[0][@"name"]);
                    
                     LineTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                    cell.startL.text = self.dataArray[0][@"name"];
                    
                    [self.postDic setObject:self.dataArray[0][@"name"] forKey:@"departProvinceName"] ;
                    [self.postDic setObject:self.dataArray[0][@"code"] forKey:@"departProvinceCode"] ;

                    
                    
                } else {
                    
                    if (_isDelete == 0) {
                        
                        [self initPickerVIew];

                    }
                    

                }
                
                
                
                [self.tableView reloadData];
                
            }
            
        } else {
            
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];

        }
        
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
   }



-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
